import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Upload, Button, Card, Row, Col, message } from 'antd';
import { InboxOutlined, DownloadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import Link from 'next/link';
import ReactCrop, { centerCrop, makeAspectCrop } from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import Layout from '../../components/layout/Layout';
import styles from '../../styles/ToolDetail.module.css';

const { Dragger } = Upload;

// 创建裁剪帮助函数
function generateDownload(canvas, crop) {
  if (!crop || !canvas) {
    return;
  }

  canvas.toBlob(
    (blob) => {
      if (!blob) {
        console.error('Canvas is empty');
        return;
      }
      return blob;
    },
    'image/jpeg',
    0.95
  );
}

const ImageCropPage = () => {
  const [originalImage, setOriginalImage] = useState(null);
  const [crop, setCrop] = useState({
    unit: '%',
    width: 50,
    height: 50,
    x: 25,
    y: 25,
    aspect: 16 / 9
  });
  const [completedCrop, setCompletedCrop] = useState(null);
  const [croppedImage, setCroppedImage] = useState(null);
  const [aspectRatio, setAspectRatio] = useState('16:9');
  const [loading, setLoading] = useState(false);
  const [debugInfo, setDebugInfo] = useState(null);
  const [fileInfo, setFileInfo] = useState({ type: 'image/jpeg' });
  const imgRef = useRef(null);
  const previewCanvasRef = useRef(null);
  const [currentDimensions, setCurrentDimensions] = useState({ width: 0, height: 0 });
  
  // 设置居中裁剪 - 使用图片最小边作为基准
  const centerAspectCrop = (mediaWidth, mediaHeight, aspect) => {
    // 计算基于最小边的最大裁剪区域
    let cropSize;
    
    if (aspect) {
      // 有固定比例，需要考虑宽高比
      if (aspect > 1) {
        // 宽大于高的比例 (如 16:9, 4:3)
        // 以高度为基准计算最大宽度
        const maxHeight = Math.min(mediaHeight, mediaWidth / aspect);
        cropSize = {
          width: maxHeight * aspect,
          height: maxHeight
        };
      } else if (aspect < 1) {
        // 高大于宽的比例 (如 9:16, 3:4)
        // 以宽度为基准计算最大高度
        const maxWidth = Math.min(mediaWidth, mediaHeight * aspect);
        cropSize = {
          width: maxWidth,
          height: maxWidth / aspect
        };
      } else {
        // 正方形 (1:1)
        // 使用最小边作为尺寸
        const size = Math.min(mediaWidth, mediaHeight);
        cropSize = {
          width: size,
          height: size
        };
      }
    } else {
      // 无固定比例，使用最小边的90%
      const size = Math.min(mediaWidth, mediaHeight) * 0.9;
      cropSize = {
        width: size,
        height: size
      };
    }
    
    // 计算百分比
    const percentWidth = (cropSize.width / mediaWidth) * 100;
    const percentHeight = (cropSize.height / mediaHeight) * 100;
    
    // 居中计算起始位置
    const x = (mediaWidth - cropSize.width) / 2;
    const y = (mediaHeight - cropSize.height) / 2;
    const percentX = (x / mediaWidth) * 100;
    const percentY = (y / mediaHeight) * 100;
    
    console.log('计算默认裁剪区域:', {
      mediaWidth, mediaHeight,
      aspect,
      cropSize,
      percentX, percentY,
      percentWidth, percentHeight
    });
    
    return {
      unit: '%',
      x: percentX,
      y: percentY,
      width: percentWidth,
      height: percentHeight,
      aspect
    };
  };

  // 当裁剪区域变化时更新尺寸信息
  useEffect(() => {
    if (completedCrop && imgRef.current) {
      const { naturalWidth, naturalHeight } = imgRef.current;
      const scaleX = naturalWidth / imgRef.current.width;
      const scaleY = naturalHeight / imgRef.current.height;
      
      const realWidth = Math.round(completedCrop.width * scaleX);
      const realHeight = Math.round(completedCrop.height * scaleY);
      
      setCurrentDimensions({
        width: realWidth,
        height: realHeight
      });
    }
  }, [completedCrop]);

  // 上传前检查文件
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片必须小于5MB!');
      return false;
    }
    
    // 保存文件信息
    setFileInfo({
      type: file.type,
      name: file.name,
      size: file.size
    });
    
    // 显示原始图片预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setOriginalImage(reader.result);
      setCroppedImage(null);  // 清除之前的裁剪结果
      setCompletedCrop(null); // 清除之前的裁剪设置
      setCurrentDimensions({ width: 0, height: 0 });
      setDebugInfo(null); // 清除之前的调试信息
    };
    
    return false;  // 阻止自动上传
  };

  // 重写handleAspectRatioChange函数，保留用户选择的区域
  const handleAspectRatioChange = (value) => {
    setAspectRatio(value);
    
    let aspect = null;
    switch (value) {
      case '1:1':
        aspect = 1;
        break;
      case '4:3':
        aspect = 4/3;
        break;
      case '16:9':
        aspect = 16/9;
        break;
      case 'free':
        aspect = null;
        break;
      default:
        aspect = 16/9;
    }
    
    console.log('切换裁剪比例:', value, '计算aspect值:', aspect);
    
    if (imgRef.current) {
      const { width, height } = imgRef.current;
      console.log('图像当前尺寸:', width, 'x', height);
      
      // 使用自定义的centerAspectCrop计算最优的裁剪区域
      const newCrop = centerAspectCrop(width, height, aspect);
      
      console.log('新的裁剪区域:', newCrop);
      setCrop(newCrop);
      setCompletedCrop(newCrop);
    } else {
      console.log('imgRef不存在，只更新aspect值');
      setCrop({ ...crop, aspect });
    }
  };

  // 图片加载完成时的回调
  const onImageLoad = (e) => {
    const { width, height } = e.currentTarget;
    imgRef.current = e.currentTarget;
    
    // 设置初始裁剪区域 - 使用最小边为基准
    const aspect = aspectRatio === 'free' ? null : 
                  aspectRatio === '1:1' ? 1 :
                  aspectRatio === '4:3' ? 4/3 : 16/9;
    
    // 使用自定义的centerAspectCrop计算最优的裁剪区域
    const newCrop = centerAspectCrop(width, height, aspect);
    
    console.log('图片加载完成，设置初始裁剪区域:', newCrop);
    setCrop(newCrop);
    // 初始化completedCrop，以便裁剪按钮可用
    setCompletedCrop(newCrop);
  };

  // 创建图像的辅助函数 - 使用原生DOM API
  const createImage = (url) =>
    new Promise((resolve, reject) => {
      const image = new Image();
      image.addEventListener('load', () => resolve(image));
      image.addEventListener('error', (error) => reject(error));
      image.setAttribute('crossOrigin', 'anonymous');
      image.src = url;
    });

  // 直接绘制到Canvas的方法
  const drawImageToCanvas = (image, canvas, crop, scale = 1) => {
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      throw new Error('无法获取canvas上下文');
    }

    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 设置白色背景 - 防止透明区域显示为黑色
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 计算裁剪坐标和尺寸
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    
    const cropX = Math.round(crop.x * scaleX);
    const cropY = Math.round(crop.y * scaleY);
    const cropWidth = Math.round(crop.width * scaleX);
    const cropHeight = Math.round(crop.height * scaleY);
    
    // 打印调试信息到控制台
    console.log('绘制图像信息:', {
      imageWidth: image.width,
      imageHeight: image.height,
      naturalWidth: image.naturalWidth,
      naturalHeight: image.naturalHeight,
      cropX, cropY, cropWidth, cropHeight,
      canvasWidth: canvas.width,
      canvasHeight: canvas.height
    });
    
    // 绘制图像
    try {
      ctx.drawImage(
        image,
        cropX,
        cropY,
        cropWidth,
        cropHeight,
        0,
        0,
        canvas.width,
        canvas.height
      );
    } catch (error) {
      console.error('绘制图像时出错:', error);
      // 尝试使用备用方法
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
    }
    
    return canvas;
  };

  // 生成包含图片的HTML
  const renderImageHTML = (width, height, dataUrl) => {
    return `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>裁剪图片</title>
        <style>
          body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: transparent;
          }
          img {
            max-width: 100%;
            height: auto;
            display: block;
          }
        </style>
      </head>
      <body>
        <img src="${dataUrl}" width="${width}" height="${height}" alt="裁剪后的图片">
      </body>
      </html>
    `;
  };

  // 执行裁剪
  const handleCrop = async () => {
    if (!imgRef.current || !completedCrop) {
      message.warning('请先上传图片并设置裁剪区域');
      return;
    }
    
    setLoading(true);
    setDebugInfo(null);
    
    let debug = {
      cropDetails: {...completedCrop},
      imageInfo: {},
      cropCalculation: {},
      attempts: []
    };
    
    try {
      const image = imgRef.current;
      
      // 获取原始图像尺寸
      const { naturalWidth, naturalHeight } = image;
      const displayWidth = image.width;
      const displayHeight = image.height;
      
      // 计算缩放比例
      const scaleX = naturalWidth / displayWidth;
      const scaleY = naturalHeight / displayHeight;
      
      // 记录调试信息
      console.log('裁剪开始 ==========');
      console.log('裁剪比例:', aspectRatio);
      console.log('原始图像尺寸:', naturalWidth, 'x', naturalHeight);
      console.log('显示图像尺寸:', displayWidth, 'x', displayHeight);
      console.log('缩放比例:', scaleX, scaleY);
      console.log('裁剪区域(显示尺寸):', completedCrop);
      
      debug.imageInfo = {
        naturalWidth,
        naturalHeight,
        displayWidth,
        displayHeight,
        scaleX,
        scaleY
      };
      
      // 计算实际裁剪坐标和尺寸
      let cropX, cropY, cropWidth, cropHeight;
      
      // 根据裁剪区域单位计算实际像素坐标
      if (completedCrop.unit === '%') {
        // 百分比单位，转换为像素
        cropX = Math.round((completedCrop.x / 100) * displayWidth * scaleX);
        cropY = Math.round((completedCrop.y / 100) * displayHeight * scaleY);
        cropWidth = Math.round((completedCrop.width / 100) * displayWidth * scaleX);
        cropHeight = Math.round((completedCrop.height / 100) * displayHeight * scaleY);
      } else {
        // 像素单位，直接应用缩放
        cropX = Math.round(completedCrop.x * scaleX);
        cropY = Math.round(completedCrop.y * scaleY);
        cropWidth = Math.round(completedCrop.width * scaleX);
        cropHeight = Math.round(completedCrop.height * scaleY);
      }
      
      // 1:1比例特别处理
      if (aspectRatio === '1:1') {
        console.log('检测到1:1比例裁剪，使用特殊处理逻辑');
        
        // 确保宽高完全相等
        const size = Math.min(cropWidth, cropHeight);
        
        // 调整裁剪区域，确保保持正方形且居中
        const diffWidth = cropWidth - size;
        const diffHeight = cropHeight - size;
        
        cropX += Math.floor(diffWidth / 2);
        cropY += Math.floor(diffHeight / 2);
        cropWidth = size;
        cropHeight = size;
        
        console.log('1:1特殊处理后的裁剪尺寸:', cropWidth, 'x', cropHeight);
      }
      
      // 记录调试信息
      debug.cropCalculation = {
        cropX,
        cropY,
        cropWidth,
        cropHeight,
        unit: completedCrop.unit
      };
      
      console.log('实际裁剪坐标和尺寸:', cropX, cropY, cropWidth, cropHeight);
      
      // 检查裁剪区域是否过小
      const minSize = Math.min(naturalWidth, naturalHeight) * 0.1; // 至少为原图的10%
      if (cropWidth < minSize || cropHeight < minSize) {
        console.warn('裁剪区域过小，自动调整至', minSize, 'x', minSize);
        
        // 保持中心点不变，扩大尺寸
        const centerX = cropX + (cropWidth / 2);
        const centerY = cropY + (cropHeight / 2);
        
        cropWidth = Math.max(cropWidth, minSize);
        cropHeight = Math.max(cropHeight, minSize);
        
        cropX = centerX - (cropWidth / 2);
        cropY = centerY - (cropHeight / 2);
      }
      
      // 检查裁剪区域是否有效
      if (cropX < 0 || cropY < 0 || cropX + cropWidth > naturalWidth || cropY + cropHeight > naturalHeight) {
        console.warn('警告：裁剪区域超出图片范围，进行调整');
        cropX = Math.max(0, cropX);
        cropY = Math.max(0, cropY);
        cropWidth = Math.min(cropWidth, naturalWidth - cropX);
        cropHeight = Math.min(cropHeight, naturalHeight - cropY);
        console.log('调整后的裁剪区域:', cropX, cropY, cropWidth, cropHeight);
      }
      
      // 检查裁剪区域尺寸
      if (cropWidth <= 0 || cropHeight <= 0) {
        message.error({ content: '无效的裁剪区域，请重新选择', key: 'crop' });
        setLoading(false);
        return;
      }
      
      // 更新当前尺寸，确保显示正确
      setCurrentDimensions({
        width: cropWidth,
        height: cropHeight
      });
      
      // 最小裁剪尺寸检查
      if (cropWidth < 10 || cropHeight < 10) {
        message.error({ content: '裁剪区域太小，请选择更大的区域', key: 'crop' });
        setLoading(false);
        return;
      }
      
      // 创建离屏Canvas进行裁剪
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      // 设置Canvas尺寸为裁剪尺寸
      canvas.width = cropWidth;
      canvas.height = cropHeight;
      
      console.log('Canvas尺寸设置为:', canvas.width, 'x', canvas.height);
      
      try {
        // 设置白色背景
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制裁剪后的图像
        console.log('尝试绘制图像，参数:', {
          imageObj: image,
          sourceX: cropX,
          sourceY: cropY,
          sourceWidth: cropWidth,
          sourceHeight: cropHeight,
          destX: 0,
          destY: 0,
          destWidth: cropWidth,
          destHeight: cropHeight
        });
        
        ctx.drawImage(
          image,
          cropX,
          cropY,
          cropWidth,
          cropHeight,
          0,
          0,
          cropWidth,
          cropHeight
        );
        
        // 获取像素数据检查是否有内容
        const pixelData = ctx.getImageData(0, 0, 10, 10).data;
        const hasContent = Array.from(pixelData).some(value => value !== 255); // 检查是否全是白色
        console.log('Canvas内容检查 - 是否有非白色像素:', hasContent);
        
        // 将Canvas转换为图像URL，使用保存的文件类型
        const croppedImageUrl = canvas.toDataURL(fileInfo?.type || 'image/png', 0.95);
        setCroppedImage(croppedImageUrl);
        
        // 保存调试信息
        debug.attempts.push({
          success: true,
          canvasWidth: canvas.width,
          canvasHeight: canvas.height,
          hasContent
        });
        
        setDebugInfo(debug);
        console.log('裁剪完成 ==========');
        message.success({ content: '图片裁剪成功！', key: 'crop' });
      } catch (error) {
        console.error('Canvas绘制错误:', error);
        
        debug.attempts.push({
          success: false,
          error: error.toString()
        });
        
        setDebugInfo(debug);
        
        message.error({ content: '裁剪过程中出错，请重试', key: 'crop' });
      }
    } catch (error) {
      console.error('裁剪图片错误:', error);
      
      debug.attempts.push({
        success: false,
        error: error.toString()
      });
      
      setDebugInfo(debug);
      
      message.error({ content: '裁剪图片失败，请重试', key: 'crop' });
    } finally {
      setLoading(false);
    }
  };

  // 下载裁剪后的图片
  const handleDownload = () => {
    if (!croppedImage) return;
    
    // 检查是否是dataURL
    if (croppedImage.startsWith('data:')) {
      const link = document.createElement('a');
      link.href = croppedImage;
      // 使用原始文件名（如果有）
      const fileName = fileInfo?.name ? `cropped-${fileInfo.name}` : 'cropped-image.jpg';
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
    // 检查是否是Blob URL
    else if (croppedImage.startsWith('blob:')) {
      // 对于HTML方式裁剪的结果，需要截图
      fetch(croppedImage)
        .then(response => response.blob())
        .then(blob => {
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          const fileName = fileInfo?.name ? `cropped-${fileInfo.name}` : 'cropped-image.jpg';
          link.download = fileName;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(error => {
          console.error('下载时出错:', error);
          message.error('下载失败，请重试');
        });
    }
  };

  // 重置所有设置
  const handleReset = () => {
    setOriginalImage(null);
    setCompletedCrop(null);
    setCroppedImage(null);
    setFileInfo({ type: 'image/jpeg' });
    imgRef.current = null;
    setCurrentDimensions({ width: 0, height: 0 });
    setDebugInfo(null);
  };

  return (
    <Layout title="图片裁剪 - 在线工具平台" description="在线裁剪图片，调整图片尺寸和比例">
      <div className={styles.toolHeader}>
        <div className={styles.container}>
          <Link href="/image-tools" className={styles.backLink} legacyBehavior>
            <a className={styles.backLink}>
              <ArrowLeftOutlined /> 返回图片工具
            </a>
          </Link>
          <h1 className={styles.toolTitle}>图片裁剪</h1>
          <p className={styles.toolDescription}>
            裁剪图片尺寸，调整比例，轻松获得完美构图
          </p>
        </div>
      </div>

      <div className={styles.toolContent}>
        <div className={styles.container}>
          <Card className={styles.toolCard}>
            <div className={styles.uploadSection}>
              {!originalImage && (
                <Dragger
                  name="file"
                  multiple={false}
                  beforeUpload={beforeUpload}
                  showUploadList={false}
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                  <p className="ant-upload-hint">
                    支持PNG、JPG、JPEG、WEBP格式，单个文件不超过5MB
                  </p>
                </Dragger>
              )}

              {originalImage && !croppedImage && (
                <div className={styles.cropSection}>
                  <Row gutter={[24, 24]}>
                    <Col xs={24} md={16}>
                      <div className={styles.cropContainer} style={{ maxWidth: '100%', overflow: 'hidden' }}>
                        <ReactCrop
                          crop={crop}
                          onChange={(newCrop) => {
                            setCrop(newCrop);
                            // 实时更新尺寸，即使没有完成裁剪
                            if (imgRef.current) {
                              const { naturalWidth, naturalHeight } = imgRef.current;
                              const scaleX = naturalWidth / imgRef.current.width;
                              const scaleY = naturalHeight / imgRef.current.height;
                              
                              // 计算实际像素尺寸
                              const realWidth = Math.round(newCrop.width * scaleX);
                              const realHeight = Math.round(newCrop.height * scaleY);
                              
                              setCurrentDimensions({
                                width: realWidth,
                                height: realHeight
                              });
                            }
                          }}
                          onComplete={(c) => {
                            setCompletedCrop(c);
                            // 更新完成的裁剪区域后立即更新尺寸显示
                            if (imgRef.current) {
                              const { naturalWidth, naturalHeight } = imgRef.current;
                              const scaleX = naturalWidth / imgRef.current.width;
                              const scaleY = naturalHeight / imgRef.current.height;
                              
                              setCurrentDimensions({
                                width: Math.round(c.width * scaleX),
                                height: Math.round(c.height * scaleY)
                              });
                            }
                          }}
                          aspect={aspectRatio === 'free' ? undefined : 
                                 aspectRatio === '1:1' ? 1 :
                                 aspectRatio === '4:3' ? 4/3 : 16/9}
                          ruleOfThirds
                        >
                          <img
                            src={originalImage}
                            alt="待裁剪图片"
                            onLoad={onImageLoad}
                            style={{ maxWidth: '100%' }}
                          />
                        </ReactCrop>
                      </div>
                    </Col>
                    <Col xs={24} md={8}>
                      <div className={styles.cropControls}>
                        <h3>裁剪设置</h3>
                        
                        <div className={styles.aspectRatioSelector}>
                          <p>选择裁剪比例:</p>
                          <div className={styles.aspectButtons}>
                            <Button 
                              type={aspectRatio === 'free' ? 'primary' : 'default'}
                              onClick={() => handleAspectRatioChange('free')}
                            >
                              自由比例
                            </Button>
                            <Button 
                              type={aspectRatio === '1:1' ? 'primary' : 'default'}
                              onClick={() => handleAspectRatioChange('1:1')}
                            >
                              1:1
                            </Button>
                            <Button 
                              type={aspectRatio === '4:3' ? 'primary' : 'default'}
                              onClick={() => handleAspectRatioChange('4:3')}
                            >
                              4:3
                            </Button>
                            <Button 
                              type={aspectRatio === '16:9' ? 'primary' : 'default'}
                              onClick={() => handleAspectRatioChange('16:9')}
                            >
                              16:9
                            </Button>
                          </div>
                        </div>
                        
                        {currentDimensions.width > 0 && currentDimensions.height > 0 && (
                          <div className={styles.dimensionsInfo} style={{ margin: '15px 0', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                            <p style={{ margin: 0 }}>
                              <strong>当前尺寸:</strong> {currentDimensions.width} × {currentDimensions.height} 像素
                            </p>
                            <p style={{ margin: '5px 0 0 0' }}>
                              <strong>比例:</strong> {aspectRatio === 'free' ? '自由比例' : aspectRatio}
                            </p>
                          </div>
                        )}
                        
                        <div className={styles.cropActions} style={{ marginTop: '20px' }}>
                          <Button 
                            type="primary" 
                            onClick={handleCrop} 
                            loading={loading}
                            block
                          >
                            确认裁剪
                          </Button>
                          <Button onClick={handleReset} style={{ marginTop: '10px' }} block>
                            重新上传
                          </Button>
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
              )}

              {croppedImage && (
                <div className={styles.resultSection}>
                  <h3>裁剪结果</h3>
                  
                  <Row gutter={24} className={styles.compareRow}>
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>原始图片</h4>
                        <div className={styles.imagePreview}>
                          <img src={originalImage} alt="原始图片" style={{ maxWidth: '100%' }} />
                        </div>
                      </div>
                    </Col>
                    
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>裁剪后 ({currentDimensions.width} × {currentDimensions.height} 像素)</h4>
                        <div className={styles.imagePreview} style={{ background: '#f0f0f0', borderRadius: '4px', overflow: 'hidden' }}>
                          {croppedImage && croppedImage.startsWith('blob:') ? (
                            <iframe 
                              src={croppedImage} 
                              title="裁剪后图片" 
                              style={{ 
                                width: '100%', 
                                height: '200px', 
                                border: 'none',
                                background: 'white' 
                              }}
                            />
                          ) : (
                            <img 
                              src={croppedImage} 
                              alt="裁剪后图片" 
                              style={{ 
                                display: 'block',
                                maxWidth: '100%',
                                boxShadow: '0 1px 3px rgba(0,0,0,0.12)'
                              }} 
                            />
                          )}
                        </div>
                      </div>
                    </Col>
                  </Row>
                  
                  <div className={styles.actionButtons}>
                    <Button
                      type="primary"
                      icon={<DownloadOutlined />}
                      size="large"
                      onClick={handleDownload}
                    >
                      下载裁剪图片
                    </Button>
                    
                    <Button
                      onClick={() => {
                        setCroppedImage(null);
                        setDebugInfo(null);
                      }}
                      style={{ marginLeft: '10px' }}
                    >
                      重新裁剪
                    </Button>
                    
                    <Button
                      onClick={handleReset}
                      style={{ marginLeft: '10px' }}
                    >
                      重新上传
                    </Button>
                  </div>
                  
                  {/* 总是显示调试信息，帮助识别问题 */}
                  <div style={{ marginTop: '20px', padding: '15px', background: '#f9f9f9', borderRadius: '4px', fontSize: '12px' }}>
                    <h4>调试信息</h4>
                    <p>裁剪比例: {aspectRatio}</p>
                    <p>图片尺寸: {currentDimensions.width} × {currentDimensions.height} 像素</p>
                    {debugInfo && (
                      <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', maxHeight: '200px', overflow: 'auto' }}>
                        {JSON.stringify(debugInfo, null, 2)}
                      </pre>
                    )}
                  </div>
                </div>
              )}
            </div>
          </Card>
          
          <div className={styles.toolTips}>
            <h3>使用提示</h3>
            <ul>
              <li>上传图片后，拖动或调整裁剪框的位置和大小</li>
              <li>可以选择不同的裁剪比例，包括自由比例、1:1（正方形）、4:3和16:9</li>
              <li>裁剪框下方会实时显示当前所选区域的尺寸和比例</li>
              <li>确认裁剪后，可以预览裁剪结果并下载裁剪后的图片</li>
              <li>为获得最佳效果，建议使用清晰度较高的原始图片</li>
              <li>如果遇到黑色图片问题，请尝试使用不同的浏览器或图片格式</li>
            </ul>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default ImageCropPage; 